<?php
declare (strict_types = 1);

namespace app\controller\api\v1\user\order;

use app\controller\api\ApiController;
use app\exception\LogicException;
use app\service\logic\common\order\OrderConsultService;
use app\service\logic\common\order\OrderMultiService;
use app\validate\common\order\ConsultValidate;
use app\validate\common\order\MultiValidate;
use Carbon\Carbon;
use think\App;
use think\response\Json;
use think\db\exception\DbException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Config;

class MultiController extends ApiController
{
    protected $service;

    public function __construct(App $app, OrderMultiService $service)
    {
        parent::__construct($app);

        $this->service = $service;
    }

    /**
     * 测试记录
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(): Json
    {
        $params = $this->request->param();
        $search_fields = $this->service->getSearchColumn();
        $search = request()->only($search_fields);

        $this->validate($params, MultiValidate::class . '.index');
        $user = $this->request->middleware('user');
        $search['user_id'] = $user['id'];
        $search['state'] = 1;

        $fun = function ($item) {
            unset($item['belongMulti']);
            return $item;
        };
        $result = $this->service->getList($params, $search_fields, $search, ['belongMulti'], $fun);
        return amis($result);
    }

    /**
     * 获取所有题目
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws LogicException
     */
    public function topic()
    {
        $params = $this->request->param();
        $this->validate($params, MultiValidate::class . '.topic');

        $result = $this->service->topic($params);
        return amis($result);
    }

    /**
     * 开始答题(一题一答)
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws LogicException
     * @throws ModelNotFoundException
     */
    public function answer()
    {
        $params = $this->request->param();
        $this->validate($params, MultiValidate::class . '.answer');

        $result = $this->service->answer($params);
        return amis($result);
    }

    /**
     * 开始答题(全部完成)
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws LogicException
     * @throws ModelNotFoundException
     */
    public function answers()
    {
        $params = $this->request->param();
        $this->validate($params, MultiValidate::class . '.answers');

        $result = $this->service->answers($params);
        return amis($result);
    }

    /**
     * 查看结果
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws LogicException
     * @throws ModelNotFoundException
     */
    public function result()
    {
        $params = $this->request->param();
        $this->validate($params, MultiValidate::class . '.result');

        $result = $this->service->result($params);
        return amis($result);
    }

    /**
     * 多元题型量表解读师列表
     *
     * @return Json
     */
    public function interpreter()
    {
        $params = $this->request->param();
        $this->validate($params, MultiValidate::class . '.interpreter');

        $result = $this->service->interpreter($params);
        return amis($result);
    }

    /**
     * 解读专家详情
     *
     * @return Json
     */
    public function interpreterRead()
    {
        $params = $this->request->param();
        $this->validate($params, MultiValidate::class . '.interpreterRead');

        $result = $this->service->interpreterRead($params);
        return amis($result);
    }

    /**
     * 预约量表解读师付款
     *
     * @return Json
     */
    public function payment()
    {
        $params = $this->request->param();
        $this->validate($params, ConsultValidate::class . '.interpreter');
        $user = $this->request->middleware('user');
        $params['user_id'] = $user['id'];

        // 生成订单
        $order = invoke(OrderConsultService::class)->createFromInterpret($params);
        // 根据支付类型
        $payment = invoke(OrderConsultService::class)->payment($order);
        // $payment = invoke(OrderConsultService::class)->paymentPage($order); // debug
        return amis([
            'order' => $order,
            'payment' => $payment,
        ]);
    }

    /**
     * 待支付订单重新发起支付
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws LogicException
     * @throws ModelNotFoundException
     */
    public function repay()
    {
        $params = $this->request->param();
        $this->validate($params, MultiValidate::class . '.repay');
        $user = $this->request->middleware('user');
        $params['user_id'] = $user['id'];

        $result = $this->service->repay($params);
        return amis($result);
    }

    // function getOptions()
    // {
    //     /** 初始化 **/
    //     $options = new Config();
    //
    //     /** 通信协议 **/
    //     $options->protocol = 'https';
    //
    //     /** 支付宝网关 **/
    //     $options->gatewayHost = 'openapi.alipaydev.com';
    //
    //     /** 设置签名类型 **/
    //     $options->signType = 'RSA2';
    //
    //     /** 应用id,如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
    //     $options->appId = '2021000119695999';
    //
    //     /** 应用私钥, 如何获取请参考：https://opensupport.alipay.com/support/helpcenter/207/201602471154?ant_source=antsupport **/
    //     $options->merchantPrivateKey = 'MIIEpAIBAAKCAQEAwd5ws9BDE3YpvZhJGNCebaDjwDXbHchoqg+dUmTa/TkoTyQg9gRBiTBAPl8hTmwOZl4ALWokXgo3cBCw5KF25XOhQpn/PQmhLdqMi/qj+VYLfvulgH7EsNByTQHrhLDkr8AcFK3NXZf3GgmchenPJjjxi9mRFjGC1CpMBMy2KbdakGxnKcI5xecGQYUeRPH7KTlA/ir0H/+Jh+mYvC2rN7ShAOhDhO1U6gnU0TA+keyqxr6TkOll9KTkG1a7icpbQOZO94vTlsOS7Y9FPlI9ucGjc4U0gvpFBt3qxV4cayIE0V124RkNDA7HEISpWsl+TWqy7IBdgYEZDG2b6xXZ/wIDAQABAoIBAHM88ekwpm5vEqisWObzOvkXZcnfOXweoHhWB8HuSW20CA3i/+S86ufNUqLAkV+4Q2b+AUT9jtiHYiSvBzcf8zi43uZj+6AglTpYaqraNZYEW5kDpIEY2XnwrcCwn3qkW4tMumRgW26C4lML24qOTJ//wTTMAr4aeBX9fmpr9OweFFHVw1irhi5nJXvqzCMTUlevYznwAPzh+fN5y2L3ohYXaRj3+lNk6rqgKh7lqwopisY1RED5XZ4WQccxQUiT+ylTqFg9GAB14YbHQ8H5nlRN3WZWFQ0j7nnGgnklX9LxZ+z7M3MP9G1WIZwPxExP6FHeIoaTNtLMg03pC1EZTIECgYEA3wHYZOSAu3irY0J2iyuTG4MjPKhygb/jRwrZwn3Q9enTthZVLcO6YZSxctVxfybDdfIQfPs2zfydApbNqvJjuS2ZF4DCe2aOMjlBG3VSbU7NGi2DLSMsBld/5E2xrc0UlxHABhJ2X196svuaSRLF0G1L2AU2r0FIA2o/ngKNJdECgYEA3o0DevXM7BX/SN4XpJfjlSkcVS6cpKekPsXMDXcy9YJ+Uu2C8zFQZztNkwNX2fE+C4l5rxTwFgOfrxCy9jAqzseG0yF6kEXG6R/qT+RNLAnTsZhQIPSoPNwttbgMlIUSlpTTt/LckE3aWRgxNvWHAA9yEv5G1SQZ6/REzNFzZs8CgYBscH1FMkfW4WqVra/vJJU3/6CW0mI77Y8a8I/LH1sI+VbVaC6rPk3XPXK8IEY8SiEprTePTqjrqTbAF4yS36LWXPHgl9/6GXhzu5uJOpeGR5c8b30l6cBypQGvhogrt1mXzC3PxhKBdfA4MFhpyBMgssT6mi5pMhlOb8/Xie4QwQKBgQCoU537RajONEEXOyxEyMFQ03xjjVLbUxTuiaqx0KORgDbNwGlYScdXnUoqVNAAvu+/yCZqX3rMG8eOoSHLBVmLduyqCltqfexZ7VLLRJF+KpycaejJVGNfTOWh2WhieVg63qxYKG/dEZWB58Npn0GRsR0F8p9enOSiS+oxxIX1jwKBgQCba6AFiy1jqBlBd/3ox8im7hXDsYVyVeoMA68fpu8YXbcZ19fz2Upn9N640TbpPsW0GX4jejgrr3S2TXpmQbQ9tHB4zFtA0FE8Av6aaWGyXIpEYHok8X3dbcU6F4d3FpRYWt3QC9oy+SWMMlPlaTvjeVw/RK4Gk+JLTr3DKwZSEQ==';
    //
    //     /** 注:如采用证书模式,无需赋值下面的支付宝公钥字符串 **/
    //     //$options->alipayCertPath = '<-- 请填写您的支付宝公钥证书文件路径，例如：/foo/alipayCertPublicKey_RSA2.crt -->';
    //     //$options->alipayRootCertPath = '<-- 请填写您的支付宝根证书文件路径，例如：/foo/alipayRootCert.crt -->';
    //     //$options->merchantCertPath = '<-- 请填写您的应用公钥证书文件路径，例如：/foo/appCertPublicKey_2019051064521003.crt -->';
    //
    //     /** 注:如采用非证书模式,则无需赋值上面的三个证书路径,改为赋值如下的支付宝公钥字符串即可 **/
    //     $options->alipayPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyS+Re4wal9bUPVnlpo3kp8Y+jWQ8yecpNCNZiu6vqKLAuHw+jyB66CzoXsmPnTwFfslLStU9Vvgt3D2YBBLAroiJY0G4FV/rBxLM8O41KtqIqZCoyhvqwfSdipSw6L/QPvXCe3lOo90JITyf+LWVjJ8exfY551hjwwwHkIjf/BEGT9LxiRX1iYa4zvNmBdxWtk4MDQ2SxDGGa/PVwRlO6YEEHS2KUEUQmJWVs2p0yjJ2KpRCuJ19UxdzIwEtMvA9PPuTQqqe504oBtu5/cveuDkyNW/2MZSWUUc9uXPU6D4YWvWghU6leTVUox+eE6P3MCOrxF9i9j/kwnz2sJv9xQIDAQAB';
    //
    //     /** 可设置异步通知接收服务地址(可选) **/
    //     //$options->notifyUrl = "<-- 请填写您的支付类接口异步通知接收服务地址，例如：https://www.test.com/callback -->";
    //
    //     /** 可设置AES密钥调用AES加解密相关接口时需要(可选)  * */
    //     $options->encryptKey = "pHHVqDDxcRKI/vDcOgy/bw==";
    //     return $options;
    // }

    /**
     * debug 结束删除
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws LogicException
     * @throws ModelNotFoundException
     */
    public function repayPage()
    {
        $params = $this->request->param();
        $this->validate($params, MultiValidate::class . '.repay');
        $user = $this->request->middleware('user');
        $params['user_id'] = $user['id'];

        $result = $this->service->repayPage($params);
        return amis($result);

        // Factory::setOptions($this->getOptions());
        //
        // try {
        //     /** 发起API调用 **/
        //     $result = Factory::payment()->Page()
        //
        //         /** 调用agent扩展方法，设置app_auth_token，完成ISV代调用 **/
        //         //->agent("ca34ea491e7146cc87d25fca24c4cD11")
        //
        //         /** 调用optional扩展方法，完成可选业务参数（biz_content下的可选字段）的设置 **/
        //         //->optional("body", "优惠购iphone12")
        //
        //         /** 入参顺序为:
        //          * subject -> 商品名称
        //          * out_trade_no -> 商户订单号，商户自定义，需保证在商户端不重复
        //          * total_amount -> 订单金额，精确到小数点后两位
        //          * return_url -> 支付完成同步跳转地址，用于用户视觉感知支付已成功，传值外网可以访问的地址
        //          **/
        //         // ->Pay("Apple iPhone11 128G", "144857ddw887ew112234", "0.02","https://alipay.com/return");
        //         ->Pay("Apple iPhone11 128G", md5('TEMP' . Carbon::now()->timestamp), "0.01","https://alipay.com/return");
        //
        //     /** 获取接口调用结果 **/
        //     // echo  json_encode($result,JSON_UNESCAPED_UNICODE);
        //     echo $result->body;
        //
        // } catch (\Exception $e) {
        //     echo "调用失败，". $e->getMessage(). PHP_EOL;;
        // }
    }

    /**
     * 查询订单支付结果
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function payR()
    {
        $params = $this->request->param();
        $this->validate($params, MultiValidate::class . '.id');

        $order = $this->service->getSimpleDetail($params);
        $result = ['result' => 1 == $order['type'] ? '2' : '1'];
        return amis($result);
    }
}
